#Covariate balance tables
cov_tab <- function(y, forcing, cluster){
  out <- rdrobust(y = y, x = forcing, c = 0, kernel = 'uniform', cluster = cluster, vce = "hc2")
  c(Estimate = round(out$coef[3,1],2), 
    `Robust SE` = round(out$se[3,1],2), 
    `Robust CI` = paste0("(",round(out$ci[3,1],2),", ", round(out$ci[3,2],2), ")"),
    `p value` = round(out$pv[3,1],3),
    `N` = sum(out$N),
    `Effective N` = sum(out$N_h),
    `Bandwidth` = round(c(out$bws[1,1]),2))
} 

#Main results table
table_m <- function(dv, running, cluster = NULL){
  out <- rdrobust(y = dv, x = running, kernel = "uniform", cluster = cluster, vce = "hc2")
  c(Estimate = round(out$coef[3,1],2), 
    `Robust CI` = paste0("(",round(out$ci[3,1],2),", ", round(out$ci[3,2],2), ")"),
    `Robust SE` = round(out$se[3,1],2), 
    `p value` = round(out$pv[3,1],4),
    `N` = sum(out$N),
    `Effective N` = sum(out$N_h),
    `Bandwidth` = round(c(out$bws[1,1], out$bws[1,2]),2))
}


#Control
table_c <- function(dv, running, cluster = NULL, control = NULL){
  out <- rdrobust(y = dv, x = running, kernel = "uniform", cluster = cluster, covs = control, vce = "hc2")
  c(Estimate = round(out$coef[3,1],2), 
    `Robust CI` = paste0("(",round(out$ci[3,1],2),", ", round(out$ci[3,2],2), ")"),
    `Robust SE` = round(out$se[3,1],2), 
    `p value` = round(out$pv[3,1],4),
    `N` = sum(out$N),
    `Effective N` = sum(out$N_h),
    `Bandwidth` = round( c(out$bws[1,1], out$bws[1,2]),2))
}


# bandwidth sensitivity
create_bw_plot <- function(data, cluster = NULL){
  df <- NULL
  for(i in 13:26){
    out1 <- rdrobust(y = data$met_effective, x = data$distance_garner, kernel = "uniform", h = i, cluster = cluster, vce = "hc2")
    out2 <- rdrobust(y = data$fairness_score, x = data$distance_garner, kernel = "uniform", h = i, cluster = cluster, vce = "hc2")
    out3 <- rdrobust(y = data$engage_score, x = data$distance_garner, kernel = "uniform", h = i, cluster = cluster, vce = "hc2")
    out4 <- rdrobust(y = data$effectiveness_score, x = data$distance_garner, kernel = "uniform", h = i, cluster = cluster, vce = "hc2")
    row1 <- c(out1$coef[3,1],out1$ci[3,1],(out1$ci[3,2]), "Satisfaction", bandwidth = i)
    row2 <- c(out2$coef[3,1],out2$ci[3,1],(out2$ci[3,2]), "Fairness", bandwidth = i)
    row3 <- c(out3$coef[3,1],out3$ci[3,1],(out3$ci[3,2]), "Engagement", bandwidth = i)
    row4 <- c(out4$coef[3,1],out4$ci[3,1],(out4$ci[3,2]), "Effectiveness", bandwidth = i)
    df <- rbind(df, row1, row2, row3, row4)
  }
  
  df <- as.data.frame.matrix(df)
  
  return(df)
}
